import logging
from django.contrib import admin
from .models import User, Account
from django import forms
from .tasks import start_ws_process, remove_ws_process
# Register your models here.
logger = logging.getLogger(__name__)

class UserCreationForm(forms.ModelForm):
    """创建用户表单
    """
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
    password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('name', 'mobile', 'email', 'account')

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("两次输入密码不一致")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserAdmin(admin.ModelAdmin):
    form = UserCreationForm

    list_display = ('name', 'mobile', 'email', 'account', 'is_active')

    search_fields = ('name', 'nickname', 'mobile')
    list_select_related = ['account']


class AccountAdmin(admin.ModelAdmin):

    list_display = ('name', 'is_testnet')
    actions = ['really_delete_selected']
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        logger.info(f"为账户{obj.name}创建配置，并启动运行进程")
        start_ws_process.delay(obj.id)

    # 无法作用与多选删除功能
    def delete_model(self, request, obj):
        """删除数据
        """
        logger.info(f'将删除交易所帐号 {obj.name}，并去除已创建的配置文件和进程')
        remove_ws_process.delay(obj.name)
        super().delete_model(request, obj)

    def get_actions(self, request):
        actions = super(AccountAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def really_delete_selected(self, request, queryset):
        for obj in queryset:
            logger.info(f'将删除交易所帐号 {obj.name}，并去除已创建的配置文件和进程')
            remove_ws_process.delay(obj.name)
            obj.delete()
        if queryset.count() == 1:
            message_bit = "1 bitmex账号 "
        else:
            message_bit = "%s bitmex账号" % queryset.count()
        self.message_user(request, "%s 成功删除." % message_bit)

    really_delete_selected.short_description = "删除选中的单元"


admin.site.register(User, UserAdmin)
admin.site.register(Account, AccountAdmin)
